/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(function () {
    var myselfInfo = {"level":0};
    var maxMessageNum = 100; 
    init();
    
    WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf";
    var ws = new WebSocket(wsAddress);
    ws.onopen = function () {
        if ($("#userData").attr("userData") != "") {
            console.log($("#userData").attr("userData"));
            ws.send($("#userData").attr("userData"));
        }
    };
    ws.onmessage = function (event) {
        var data = event.data.split('\n');
        for (var i = 0; i < data.length; i++) {
            var messages = data[i];
//            console.log("receive msg:" + messages);

            var prefix = messages.substr(0, 4);
            var content = messages.substr(5);
            console.log("prefix"+prefix + "  content:"+content);
            
            switch (prefix) {
                case "1001":
                    loginResult(content);
                    break;
                case "1005":
                    setGuestInfo(content);
                    break;
                case "1200":
                    showOnLineUsers(content);
                    break;
                case "1110":
                    showMessage(content);
                    break;
                case "1101":
                    snedMessageResult(content);
                    break;    
                case "9001":
                    layer.msg("请登录后再发言。");
                default:
            }
        }
    };
    ws.onclose = function () {
        setTimeout(function () {
            layer.msg("无法连接到聊天室");
        }, 500);
    };
    
    ws.onerror = function () {
        reconnect();
    };
    
    function init(){
        timer();
        calHeight();
        parseMyselfInfo();
    }
    
    function parseMyselfInfo(){
        jsonStr = $("#userData").attr("userData");
        if(jsonStr.length > 0){
            jsonStr = jsonStr.replace("1000|", "");
            myselfInfo =  JSON.parse(jsonStr);
        }
    }
    
    
    function setGuestInfo(content){
        $("#guestName").html(content);
    }
    
    function timer(){
        setInterval(function(){
            $(".message_advance .message_list_2").each(function(){
                var timestamp = Date.parse(new Date());
                timestamp = timestamp / 1000;
                if (Math.abs(timestamp-$(this).attr("time"))> autoCloseMessageAdvance){
                    $(this).animate({"margin-left":"-800px"}, 1000, "linear", function(){ $(this).remove(); calHeight();});
                }
            })
        } , 1000);
    }
    
    function loginResult(content){
        var obj = JSON.parse(content)
        if (!obj.Result) {
            layer.msg("进入房间失败");
        }
    }
    
    function snedMessageResult(content){
        var obj = JSON.parse(content)
        if (!obj.Result) {
            layer.msg(obj.Msg);
        }
    }

    function showOnLineUsers(content) {
        var obj = JSON.parse(content);
        if ( typeof(obj.Data) != "undefined" && obj.Data.length >= 1 && obj.Total >= 1) {
            var userListStr = "";
            var adminListStr = "";
            for (i = 0; i < obj.Data.length; i++) {
                var level = obj.Data[i].Level;
                var userIcon = obj.Data[i].Uid<=0 ?  '/assets/home/images/identity/-1.png' : '/assets/home/images/identity/'+level+'.png'; 
                var tempStr = "";
                tempStr += '<li>';
                tempStr += '<span class="member_cell_0"><img src="'+userIcon+'"><p>' + obj.Data[i].Name + '</p></span>';
                if (level>=10000){
                    tempStr += '<span class="member_cell_2">咨询</span>';
                }else if(myselfInfo.level >=10000){
                    var Status = obj.Data[i].Status;
                    var StatusText ="恢复";
                    Status ==1 ?Status =2 : Status =1;
                    Status ==1 ?StatusText : StatusText ="禁言";
                    tempStr += '<div style="display: none;" class="onopn">';
                    tempStr += '<span data-uid=' + obj.Data[i].Uid + ' data-cid=' + obj.Data[i].ClientID + ' data-status="3" class="member_cell_2 frozen">冻结</span>';
                    tempStr += '<span data-uid='+  obj.Data[i].Uid  +' data-cid=' + obj.Data[i].ClientID + ' class="member_cell_2 notip">禁IP</span>';
                    tempStr += '<span data-uid=' + obj.Data[i].Uid + ' data-cid=' + obj.Data[i].ClientID + ' data-status='+Status+' data-cid=' + obj.Data[i].ClientID + ' class="member_cell_2 gag">'+StatusText+'</span></div>';
                }
                tempStr += '</li>';
                if (obj.Data[i].Level >= 10000) {
                    adminListStr += tempStr;
                } else {
                    userListStr += tempStr;
                }
            }
//            $(".onLineUsers").html(userListStr);
//            $(".onLineAdmins").html(adminListStr);

            $(".onLineUsers").html(adminListStr+userListStr);
            
            $(".totalOnlienUsers").html(obj.Total);
            $(".totalOnline").html(obj.Total);
        }
    }

    $(document).on("mouseover mouseout",".onLineUsers li",function(event) {
        if(event.type == "mouseover"){
            $(this).find(".onopn").show();
        }else if(event.type == "mouseout"){
            $(this).find(".onopn").hide();
        }
    });
    $(document).on( "click",".gag",function() {
        var cid = $(this).data('cid');
        var uid = $(this).data('uid');
        var status = $(this).data('status');
        var stext = $(this).text();
        $.ajax({
            type: 'get',
            url: '/ban',
            data: {cid:cid,uid:uid,status:status},
            success: function(data){
                if(data.status){
                    layer.msg(stext+'成功！');
                }else{
                    layer.msg(data.msg);
                }
            }
        })
    });
    $(document).on( "click",".frozen",function() {
        var cid = $(this).data('cid');
        var uid = $(this).data('uid');
        var status = $(this).data('status');
        var stext = $(this).text();
        $.ajax({
            type: 'get',
            url: '/ban',
            data: {cid:cid,uid:uid,status:status},
            success: function(data){
                if(data.status){
                    layer.msg(stext+'成功！');
                }else{
                    layer.msg(data.msg);
                }
            }
        })
    });
    $(document).on( "click",".notip",function() {
        var cid = $(this).data('cid');
        var uid = $(this).data('uid');
        var Ip = 'ip';
        $.ajax({
            type: 'get',
            url: '/ban',
            data: {ipcid:cid,ipuid:uid},
            success: function(data){
                if(data.status){
                    layer.msg(data.msg);
                }else{
                    layer.msg(data.msg);
                }
            }
        })
    });

    function showMessage(content) {
        var content = content.split('\n');
        var msgStr = "";
        var megStrAdvance = "";
        
        for (var i = 0; i < content.length; i++) {
            obj = JSON.parse(content[i]);
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000;
//            var msg = replace_em(obj.Data);
            var msg = obj.Data;
            console.log(Date.parse(new Date()) + " before parse: "+msg);
            console.log(Date.parse(new Date()) + " after parse: "+replace_em(msg));
            // 单条解析，有bug
//            console.log(Date.parse(new Date()) + " before parse: "+msg);
//            var objNewDiv = $('<div>',{'id':'','class':''});
//            objNewDiv.html(msg);
//            console.log(Date.parse(new Date()) + " obj html: "+objNewDiv.html());
//            objNewDiv.parseEmotion();
//            console.log(Date.parse(new Date()) +  " after parse: "+objNewDiv.html());
//            msg = objNewDiv.html();
//            console.log(Date.parse(new Date()) + " after parse: "+msg);

            var userIcon = obj.Uid<= 0 ?  '/assets/home/images/identity/-1.png' : '/assets/home/images/identity/'+obj.Level+'.png'; 
            if (obj.Level >= 10000 && Math.abs(timestamp-obj.Time) <= autoCloseMessageAdvance){
                megStrAdvance +='<div class="message_list_2" time='+timestamp+'>';
                megStrAdvance +='    <div class="message_cell_5">';
                megStrAdvance +='       <dl><dt>'+obj.Name+'</dt><dd>'+formatDateTime(obj.Time)+'</dd></dl>';
                megStrAdvance +='    </div>';
                megStrAdvance +='    <div class="message_cell_6">'+msg+'</div>';                                  
                megStrAdvance +='</div>';
                $(".message_advance").append(megStrAdvance);
                calHeight();
            }
//            else{
                msgStr += '<div class="message_list_1 ">';
                msgStr += '<div class="message_cell_1">';
                msgStr += '<ul>';
                msgStr += '<li><p>'+formatDateTime(obj.Time)+'</p></li>';
                msgStr += '<li><b><img src="'+userIcon+'"/></b></li>';
                msgStr += '</ul>';
                msgStr += '<div class="message_table_1">';
                msgStr += '<table>';
                msgStr += '<tr>';
                msgStr += '<td><strong>'+obj.Name+'</strong></td>';
                msgStr += '<td><div class="message_txt_1"><span>'+msg+'</span></div></td>';
                msgStr += '</tr>';
                msgStr += '</table>';
                msgStr += '</div>';
                msgStr += '</div>';
                msgStr += '</div>';
                appendChatMsg(msgStr);
//            }
        }
        $(".chatInfo").parseEmotion();
        $(".message_list_2").parseEmotion();
    }
    
    function calHeight() {
        var total = document.documentElement.clientHeight;
        var messageBoxHeight = total - $(".message_advance").height()- 290 - $(".message_telCell_1").height();
        $(".message_normal").css("height", messageBoxHeight);
    }

    function appendChatMsg(item) {
        $(".chatInfo").append(item);
        if ($(".chatInfo .message_list_1").length > maxMessageNum ){
            $(".chatInfo .message_list_1:first").remove();
        }
        console.log("len: " + $(".chatInfo .message_list_1").length);
        
        $(".chatInfo").scrollTop($(".chatInfo").scrollTop()+200);
    }
    
    $("#btnCommit").bind("click", function(){
	commit();
    });
        
    function commit() {
        if (!ws) {
            layer.msg("已经断开连接");
            return false;
        }
        if (!$(".msg").val()) {
            layer.msg("聊天内容不能为空");
            return false;
        }
        sendMessage($(".msg").val(), 0)
        $(".msg").val("");
        return false;
    }

    function sendMessage(msgStr, userID) {
        if (!ws) {
            layer.msg("已经断开连接");
            return false;
        }
        var prefix = "1100|";
        var msg = {data: msgStr, uid: userID};
        ws.send(prefix + JSON.stringify(msg));
    }
    
    function formatDateTime(/** timestamp=0 **/) { 
	    var ts = arguments[0] || 0;  
	    var t,y,m,d,h,i,s;  
	    t = ts ? new Date(ts*1000) : new Date(); 
	    y = t.getFullYear();  
	    m = t.getMonth()+1;  
	    d = t.getDate();  
	    h = t.getHours();  
	    i = t.getMinutes();  
	    s = t.getSeconds();  
	    // 可根据需要在这里定义时间格式  
//	    return y+'-'+(m<10?'0'+m:m)+'-'+(d<10?'0'+d:d)+' '+(h<10?'0'+h:h)+':'+(i<10?'0'+i:i)+':'+(s<10?'0'+s:s);  
	    return (h<10?'0'+h:h)+':'+(i<10?'0'+i:i);  
	}
    function Desktop(){
        var sUrl = location.href;
        var sName = "";
        alert(123);
        try{
        var WshShell = new ActiveXObject("WScript.Shell");
        var oUrlLink = WshShell.CreateShortcut(WshShell.SpecialFolders("Desktop") + "\\" + sName + ".url");
        oUrlLink.TargetPath = sUrl;oUrlLink.Save();}
        catch(e){alert("当前IE安全级别不允许操作！");
    }}
});




